package com.per.mybootall.email.service.impl;

import com.per.mybootall.email.service.EmailInter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
@Slf4j
public class EmailImpl implements EmailInter {
    @Resource
    private JavaMailSender javaMailSender;
    @Value("${mail.from}")
    private String mailFrom;

    @Override
    public void sendSimpleMail(String mailTo){
        SimpleMailMessage message=new SimpleMailMessage();
        //发件人
        message.setFrom(mailFrom);
        //收件人
        message.setTo(mailTo);
        //邮箱主题
        message.setSubject("simple mail");
        //邮箱内容
        message.setText("hello world");
        //发送=》send
        javaMailSender.send(message);
        log.info("邮件已经发送");
    }


    /**
     * 发送邮件，同时携带一个附件
     * */
    @Override
    public void sendMail(String mailTo) {
        MimeMessage message=javaMailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            //发件人
            helper.setFrom(mailFrom);
            //收件人
            helper.setTo(mailTo);
            //邮箱主题
            helper.setSubject("simple mail");
            //邮箱内容
            helper.setText("hello world", true);
            //附件地址
            FileSystemResource file = new FileSystemResource(new File("E:\\emilTest.txt"));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);
            javaMailSender.send(message);
            log.info("邮件已经发送");
        } catch (MessagingException e) {
            log.error("{}",e);
        }
    }
}
